package com.example.licenseappclient;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.stage.Stage;

import java.io.*;
import java.util.concurrent.atomic.AtomicReference;

public class HelloController {

    String serialPath ="src/main/resources/serial.txt";
    private boolean status;
    private String serial=null;

    @FXML
    private Button breakButton;

    @FXML
    private TextField StatusText;

    @FXML
    private Button PurchaseButton;

    @FXML
    private Button LoginButton;

    @FXML
    void Login(ActionEvent event) {
        if (serial==null||serial.isEmpty()) {
            Alert alert = new Alert(Alert.AlertType.NONE);
            alert.setTitle("登录");
            alert.setHeaderText("请输入序列号");

            TextField inputField= new TextField();
            alert.getDialogPane().setContent(inputField);

            ButtonType confirmButton = new ButtonType("确定", ButtonBar.ButtonData.OK_DONE);
            alert.getButtonTypes().add(confirmButton);

            AtomicReference<String> keywordRef = new AtomicReference<>();

            alert.showAndWait().filter(response->response==confirmButton).ifPresent(
                    response->{
                        keywordRef.set(inputField.getText());
                    }
            );

            serial= keywordRef.get();
            WriteSerial();
        }
        if(!serial.isEmpty()){
            try {
                System.out.println("Debug login");
                SocketHelper socketHelper = new SocketHelper("127.0.0.1",8090);
                socketHelper.sendMessage("Logi:"+serial);

                String msg= socketHelper.receiveMessage();
                System.out.println(msg);

                System.out.println("Debug msg");
                System.out.println(msg);
                Resolve(msg);

                socketHelper.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        }
    }

    public void Resolve(String msg){
        if(msg.isEmpty()) return;
        String [] rmsg = msg.split(":");

        if(rmsg.length<2) return;

        if(rmsg[0].equals("Logi")){
            if(rmsg[1].equals("OK")){
                setStatus(true);
                showAlert(Alert.AlertType.INFORMATION,"登录成功","登录成功","登录成功，欢迎使用");
            }
            if(rmsg[1].equals("Full")){
                showAlert(Alert.AlertType.INFORMATION,"登录失败","该许可证使用人数已满","请更换许可证或稍后再试");
                serial=null;
            }
            if(rmsg[1].equals("Error")){
                showAlert(Alert.AlertType.INFORMATION,"登录失败","序列号错误","请使用正确的序列号");
                serial=null;
            }
        }
    }

    private void setStatus(boolean flag){
        status=flag;
        if(status) {
            StatusText.setText("正在使用软件");
        }
        else {
            StatusText.setText(null);
        }
        breakButton.setDisable(!flag);
        LoginButton.setDisable(flag);

        new Thread(()->{
            while(status){
                try {
                    Thread.sleep(1000);
                    SocketHelper socketHelper = new SocketHelper("127.0.0.1",8090);
                    socketHelper.sendMessage("Keep:"+serial);
                    socketHelper.close();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }

    @FXML
    void breakConnect(ActionEvent event) {
        try {
            SocketHelper socketHelper = new SocketHelper("127.0.0.1",8090);
            socketHelper.sendMessage("Break:"+serial);
            socketHelper.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        setStatus(false);
    }

    @FXML
    void Purchase(ActionEvent event) {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("purchase-view.fxml"));
        Stage stage= new Stage();

        try {
            Parent root = loader.load();
            Scene scene = new Scene(root);
            stage.setScene(scene);
            stage.show();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void showAlert(Alert.AlertType type, String title, String header, String content) {
        Alert alert = new Alert(type);
        alert.setTitle(title);
        alert.setHeaderText(header);
        alert.setContentText(content);
        alert.showAndWait();
    }

    public void initialize(){
        setStatus(false);
        ReadSerial();
    }

    private void WriteSerial(){
        try {
            FileWriter fileWriter =new FileWriter(new File(serialPath));
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
            System.out.println("write");

            bufferedWriter.write(serial);
            bufferedWriter.close();
            fileWriter.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void ReadSerial(){
        try {
            FileReader fileReader = new FileReader(new File(serialPath));
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            System.out.println("read");

            serial= bufferedReader.readLine();
            bufferedReader.close();
            fileReader.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}